package trend

import (
	"context"
	"fmt"
	"k8stools/pkg/config"
	"k8stools/pkg/output"
	"net/http"
	"os"
	"time"

	"github.com/prometheus/client_golang/api"
	v1 "github.com/prometheus/client_golang/api/prometheus/v1"
	"github.com/prometheus/common/model"
)

func GetTrend(c *config.Config) {
	err := AnalyzeResourceTrends(c)
	if err != nil {
		fmt.Printf("❌ 运行失败: %v\n", err)
	}
}

func AnalyzeResourceTrends(c *config.Config) error {
	// 创建 Prometheus API client
	client, err := createPrometheusClient(c)
	if err != nil {
		return fmt.Errorf("创建 Prometheus 客户端失败: %w", err)
	}

	api := v1.NewAPI(client)
	ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
	defer cancel()

	// 构建 namespace 正则
	if len(c.NameSpace) == 0 {
		return fmt.Errorf("命名空间列表不能为空")
	}

	nsFilter := ""
	for i, ns := range c.NameSpace {
		if i > 0 {
			nsFilter += "|"
		}
		nsFilter += ns
	}
	filter := fmt.Sprintf(`namespace=~"%s"`, nsFilter)

	// 查询表达式：可自定义
	cpuQuery := fmt.Sprintf(`sum(rate(container_cpu_usage_seconds_total{%s,image!="",container!="POD"}[5m])) by (namespace, pod, container)`, filter)
	memQuery := fmt.Sprintf(`avg(container_memory_usage_bytes{%s,image!="",container!="POD"}) by (namespace, pod, container)`, filter)

	// 执行 Prometheus 查询
	cpuResult, cpuWarnings, err := api.QueryRange(ctx, cpuQuery, v1.Range{
		Start: time.Now().Add(-7 * 24 * time.Hour),
		End:   time.Now(),
		Step:  time.Hour,
	})
	if err != nil {
		return fmt.Errorf("查询 CPU 失败: %w", err)
	}
	if len(cpuWarnings) > 0 {
		fmt.Printf("CPU 查询警告: %v\n", cpuWarnings)
	}

	memResult, memWarnings, err := api.QueryRange(ctx, memQuery, v1.Range{
		Start: time.Now().Add(-7 * 24 * time.Hour),
		End:   time.Now(),
		Step:  time.Hour,
	})
	if err != nil {
		return fmt.Errorf("查询内存失败: %w", err)
	}
	if len(memWarnings) > 0 {
		fmt.Printf("内存查询警告: %v\n", memWarnings)
	}

	// 构建指标映射
	cpuData := parseMatrix(cpuResult, false) // CPU: 不需要转换单位，只乘以 1000 转成 milli
	memData := parseMatrix(memResult, true)  // 内存: 需要从 Bytes 转成 MiB

	// 表头
	headers := []string{
		"Namespace", "Deployment", "Container", "趋势标签",
		"推荐CPU Requests(m)", "推荐CPU Limits(m)", "推荐Memory Requests(Mi)", "推荐Memory Limits(Mi)",
		"日期", "平均CPU(m)", "最大CPU(m)", "平均内存(Mi)", "最大内存(Mi)",
	}

	// 数据行
	var rows [][]string

	// 遍历数据并构建 CSV 行
	for key, cpuSeries := range cpuData {
		memSeries := memData[key]

		avgCPU, maxCPU := calcAvgMax(cpuSeries)
		avgMem, maxMem := calcAvgMax(memSeries)

		// 推荐值计算
		recommendCPUReq := int(avgCPU * 1.2)
		recommendCPULim := int(maxCPU * 1.5)
		recommendMemReq := int(avgMem * 1.2)
		recommendMemLim := int(maxMem * 1.5)

		// 获取其他信息
		ns := key.namespace
		deploy := extractDeployment(key.pod)
		trend := analyzeTrend(cpuSeries) // 趋势标签
		row := []string{
			ns, deploy, key.container, trend,
			fmt.Sprintf("%d", recommendCPUReq), fmt.Sprintf("%d", recommendCPULim),
			fmt.Sprintf("%d", recommendMemReq), fmt.Sprintf("%d", recommendMemLim),
			time.Now().Format("2006-01-02"),
			fmt.Sprintf("%.0f", avgCPU), fmt.Sprintf("%.0f", maxCPU),
			fmt.Sprintf("%.0f", avgMem), fmt.Sprintf("%.0f", maxMem),
		}
		rows = append(rows, row)
	}

	// 使用增强的output包保存带时间戳的CSV文件
	if err := output.OutputDataWithTimestamp("resource_trend", headers, rows, "csv"); err != nil {
		return fmt.Errorf("保存CSV文件失败: %w", err)
	}

	return nil
}

type metricKey struct {
	namespace string
	pod       string
	container string
}

// 解析 Prometheus 查询结果
func parseMatrix(val model.Value, convertToMi bool) map[metricKey][]float64 {
	res := make(map[metricKey][]float64)
	matrix, ok := val.(model.Matrix)
	if !ok {
		return res
	}
	for _, stream := range matrix {
		key := metricKey{
			namespace: string(stream.Metric["namespace"]),
			pod:       string(stream.Metric["pod"]),
			container: string(stream.Metric["container"]),
		}
		for _, v := range stream.Values {
			value := float64(v.Value)
			if convertToMi {
				value = value / (1024 * 1024) // Bytes -> Mi
			} else {
				value = value * 1000 // CPU: cores -> milli-cores
			}
			res[key] = append(res[key], value)
		}
	}
	return res
}

// 计算平均值和最大值
func calcAvgMax(data []float64) (avg, max float64) {
	if len(data) == 0 {
		return 0, 0
	}
	total := 0.0
	max = data[0]
	for _, v := range data {
		total += v
		if v > max {
			max = v
		}
	}
	avg = total / float64(len(data))
	return
}

// 分析趋势
func analyzeTrend(data []float64) string {
	if len(data) < 2 {
		return "无趋势"
	}
	delta := data[len(data)-1] - data[0]
	if delta > 50 {
		return "上升"
	} else if delta < -50 {
		return "下降"
	} else {
		return "稳定"
	}
}

// 提取 Deployment 名称
func extractDeployment(pod string) string {
	// 假设 deployment 名为 pod-name 的前缀
	// 比如 xxx-7f9cd5b477-abc12 => xxx
	if i := len(pod); i > 0 {
		if dash := lastIndex(pod, "-"); dash > 0 {
			if second := lastIndex(pod[:dash], "-"); second > 0 {
				return pod[:second]
			}
		}
	}
	return pod
}

// 查找分隔符位置
func lastIndex(s string, sep string) int {
	for i := len(s) - 1; i >= 0; i-- {
		if string(s[i]) == sep {
			return i
		}
	}
	return -1
}

// createPrometheusClient 创建支持认证的Prometheus客户端
func createPrometheusClient(c *config.Config) (api.Client, error) {
	// 创建基本的HTTP客户端
	roundTripper := http.RoundTripper(&http.Transport{
		MaxIdleConns:    10,
		IdleConnTimeout: 30 * time.Second,
	})

	// 如果配置了认证信息，则添加相应的认证处理
	if c.PrometheusAuth != nil {
		// Basic Auth认证
		if c.PrometheusAuth.BasicAuth != nil && c.PrometheusAuth.BasicAuth.Username != "" && c.PrometheusAuth.BasicAuth.Password != "" {
			roundTripper = &basicAuthRoundTripper{
				username:  c.PrometheusAuth.BasicAuth.Username,
				password:  c.PrometheusAuth.BasicAuth.Password,
				transport: roundTripper,
			}
		}
		// Bearer Token认证
		if c.PrometheusAuth.BearerToken != "" {
			roundTripper = &bearerTokenRoundTripper{
				token:     c.PrometheusAuth.BearerToken,
				transport: roundTripper,
			}
		}
		// Bearer Token File认证
		if c.PrometheusAuth.BearerTokenFile != "" {
			roundTripper = &bearerTokenFileRoundTripper{
				tokenFile: c.PrometheusAuth.BearerTokenFile,
				transport: roundTripper,
			}
		}
	}

	// 创建Prometheus API客户端
	client, err := api.NewClient(api.Config{
		Address:      c.Prometheus,
		RoundTripper: roundTripper,
	})
	if err != nil {
		return nil, fmt.Errorf("创建Prometheus客户端失败: %w", err)
	}

	return client, nil
}

// basicAuthRoundTripper 实现Basic Auth认证的RoundTripper
type basicAuthRoundTripper struct {
	username  string
	password  string
	transport http.RoundTripper
}

func (b *basicAuthRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	req.SetBasicAuth(b.username, b.password)
	return b.transport.RoundTrip(req)
}

// bearerTokenRoundTripper 实现Bearer Token认证的RoundTripper
type bearerTokenRoundTripper struct {
	token     string
	transport http.RoundTripper
}

func (b *bearerTokenRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	req.Header.Set("Authorization", "Bearer "+b.token)
	return b.transport.RoundTrip(req)
}

// bearerTokenFileRoundTripper 实现Bearer Token File认证的RoundTripper
type bearerTokenFileRoundTripper struct {
	tokenFile string
	transport http.RoundTripper
}

func (b *bearerTokenFileRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
	token, err := os.ReadFile(b.tokenFile)
	if err != nil {
		return nil, fmt.Errorf("读取token文件失败: %w", err)
	}
	req.Header.Set("Authorization", "Bearer "+string(token))
	return b.transport.RoundTrip(req)
}
